<template>
  <div class="container">
    <PropTable
      :columns="column"
      :data="list"
      :total="total"
      @reset="reset"
      @onSubmit="onSubmit"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
      @exportExcelAction="exportExcelAction"
      permissionPrefix="system:details"
    >
      <template v-slot:state="scope">
        <div v-if="!useEmpty(scope.row.state)">
          {{ getStatusLabel(scope.row.state) }}
        </div>
      </template>
      <!-- 业主单位 所在地区 行业 -->
      <template #otherSearch>
        <el-form-item label="所在地区" style="margin: 0px 0px 0px 0px">
          <el-cascader
            v-model="addressList"
            ref="ref_areaCodes"
            :options="areaCodelist"
            :props="areaCodeprops"
            clearable
          ></el-cascader>
        </el-form-item>

        <el-form-item label="业主单位" style="margin: 0px 0px 0px 0px">
          <el-input
            class="input-item"
            v-model="enterpriseName"
            placeholder="请输入"
          ></el-input>
        </el-form-item>

        <!-- 行业 -->
        <el-form-item label="行业" style="margin: 0px 0px 0px 0px">
          <el-select
            v-model="industry"
            multiple
            filterable
            allow-create
            default-first-option
            :reserve-keyword="false"
            placeholder="请输入"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 创建时间 -->
        <el-form-item label="创建时间" style="margin: 3px 15px 3px 0px">
          <el-date-picker
            v-model="creatTime"
            type="daterange"
            range-separator="至"
            start-placeholder="请选择"
            end-placeholder="请选择"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="项目总投资额" style="margin: 3px 15px 3px 0px">
          <el-input
            clearable
            v-model="createInvestment"
            type="number"
            placeholder="最小值"
            @input="handleInput('min')"
            @blur="handleVal"
          >
          </el-input>
          <div class="center" style="margin-left: 10px; margin-right: 10px">
            <span>至</span>
          </div>
          <el-input
            clearable
            v-model="endInvestment"
            placeholder="最大值"
            type="number"
            @input="handleInput('max')"
            @blur="handleVal"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="合同工期" style="margin: 3px 15px 3px 0px">
          <el-date-picker
            v-model="datetime"
            type="daterange"
            range-separator="至"
            start-placeholder="请选择"
            end-placeholder="请选择"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </template>
      <!-- <el-icon><plus /></el-icon> -->
      <template #btn>
        <div style="display: flex; justify-content: flex-end">
          <el-button type="primary" v-if="userStore.rolescode!=15" @click="handleAdd"> 新建项目立项</el-button>
        </div>
      </template>
      <template v-slot:projectStatus="scope">
        <div>{{ stateTransition(scope.row.projectStatus) }}</div>
      </template>
      <template v-slot:projectCreateTime="scope">
        <div v-if="!useEmpty(scope.row.projectCreateTime)">
          {{ formatDate(scope.row.projectCreateTime) }}
        </div>
      </template>
      <template v-slot:operation="scope">
        <div style="display: flex; justify-content: center">
          <el-button
            v-if="scope.row.projectStatus !== '0' || userStore.rolescode==15"
            link
            type="primary"
            icon="Edit"
            @click="approvalDetail(scope.row)"
            >详情</el-button
          >
          <el-button
            v-if="
              (scope.row.projectStatus === '0' ||
              scope.row.projectStatus === '3' ||
              scope.row.projectStatus === '4')
              && userStore.rolescode!=15
            "
            link
            type="primary"
            icon="Edit"
            @click="approval(scope.row)"
          >
            编辑
          </el-button>
          <!-- 只能管理员进行删除 -->
          <el-button
            v-if="userStore.userId === 1 && userStore.rolescode!=15"
            link
            type="primary"
            icon="Delete"
            @click="delApprovalList(scope.row)"
            >删除
          </el-button>

          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handeleRevoke(scope.row)"
            v-if="scope.row.projectStatus === '2' && userStore.rolescode!=15"
          >
            撤回
          </el-button>
        </div>
      </template>
    </PropTable>
  </div>
</template>

<script setup name="projectApproval">
import { ref, onMounted } from "vue";
import PropTable from "@/components/Table/PropTable/index.vue";
import { useRouter } from "vue-router";
import { approvalList, approvalDel, withdrawApi } from "@/api/project/approval";
import {
  businessTypeList,
  location,
  industryApi,
} from "@/api/project/conversion";
import { ElMessageBox, ElMessage } from "element-plus";
import { useEmpty, formatDate } from "@/utils/index";
import useUserStore from "@/store/modules/user";
const { proxy } = getCurrentInstance();
const router = useRouter();
const loading = ref(true);
const businessoptions = ref([]);
const industry = ref("");
const userStore = useUserStore();

let statusList = [
  {
    value: "2",
    label: "计划审批中",
  },
  {
    value: "1",
    label: "立项完成",//计划审批通过
  },
  {
    value: "0",
    label: "计划审批驳回",
  },
  {
    value: "3",
    label: "计划审批撤回",
  },
  {
    value: "4",
    label: "转立项完成",
  },
];
const column = [
  {
    name: "projectName",
    label: "项目名称",
    inSearch: true,
    valueType: "input",
  },
  {
    name: "projectId",
    label: "项目编号",
    inSearch: true,
    valueType: "input",
  },
  {
    name: "projectStatus",
    label: "项目状态",
    options: statusList,
    inSearch: true,
    slot: true,
    valueType: "select",
  },
  {
    name: "investment",
    label: "项目总投资额（万元）",
    width: 180,
  },
  {
    name: "contractDuration",
    label: "工期开始",
  },
  {
    name: "contractTermination",
    label: "工期结束",
  },

  {
    name: "businessName",
    label: "业务类型",
    inSearch: true,
    valueType: "cascader",
    options: businessoptions,
    propsExpandTrigger: {
      value: "id",
      label: "businessName",
      checkStrictly: true,
      children: "children",
      emitPath: false,
    },
  },
  {
    name: "projectCreateTime",
    label: "创建时间",
    // inSearch: true,
    // valueType: "datetime",
    // slot: true,
  },
  { name: "createPerson", label: "创建人" },
  { name: "operation", slot: true, fixed: "right", width: 300, label: "操作" },
];

const addressList = ref([]);
const enterpriseName = ref("");
const createInvestment = ref();
const endInvestment = ref();
const contractDuration = ref();
const contractTermination = ref();
const areaCodelist = ref([]);
const areaCodeprops = {
  value: "id",
  label: "name",
  // checkStrictly: true,
  children: "rcDistrictList",
};
const getStatusLabel = (value) => {
  let matchedOption = statusList.find((option) => option.value === value);
  return matchedOption ? matchedOption.label : "";
};
const handelLocation = async () => {
  try {
    let params = {};
    const response = await location(params);
    if (response.code === 200 && response.data.length >= 0) {
      areaCodelist.value = response.data;
    }
  } catch (err) {
    console.log(err);
  }
};

const list = ref([]);
let pageNum = ref(1);
let pageSize = ref(10);
let total = ref(0);
const datetime = ref();
const createContract = ref();
const endContract = ref();

const creatTime = ref();
const projectCreateTime = ref();
const projecEndTime = ref();

// 处理项目状态
const stateTransition = (row) => {
  let transitions = statusList.find((item) => item.value === row);
  return transitions ? transitions.label : "";
};

const businessTypeOptions = async () => {
  let params = {};
  const response = await businessTypeList(params);
  // console.log(response);
  if (response.code === 200 && response.data.length > 0) {
    businessoptions.value = response.data;
  } else {
    console.log(err);
  }
};

const options = ref([]);
const handelIndustry = async () => {
  const res = await industryApi();
  // console.log(res);
  if (res.code === 200 && res.data) {
    options.value = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

// const businessDictionary = ref([]);
// const business = async () => {
//   try {
//     const response = await businessName();
//     if (response.code === 200 && response.data.length >= 0) {
//       businessDictionary.value = response.data;
//     }
//   } catch (err) {
//     console.log(err);
//     loading.value = false;
//   }
// };
// 新增按钮
const handleAdd = (row) => {
  router.push({
    path: "/myProject/approval/edit",
    query: { name: 1, showApproval: 1,},
  });
};

// 编辑按钮
const approval = (row) => {
  router.push({
    path: "/myProject/approval/edit",
    query: { id: row.proId, name: 2, showApproval: 1 ,status:row.projectStatus },
  });
};
// 详情按钮
const approvalDetail = (row) => {
  router.push({
    path: "/myProject/approval/edit",
    query: { id: row.proId, name: 3, showApproval: 1,status:row.projectStatus,createPerson:row.createPerson  },
  });
};
// 删除
function delApprovalList(row) {
  ElMessageBox.confirm("确定删除该项目吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    if (row && row.proId) {
      const res = await approvalDel(row.proId);
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      approvalData();
    }
  });
}
const handeleRevoke = (row) => {
  ElMessageBox.confirm("确定要撤回吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      if (row) {
        const result = await withdrawApi(row);
        if (result.code === 200) {
          // 删除成功的提示
          ElMessage.success(result.msg);
          approvalData();
        }
      }
    })
    .catch((err) => {
      // 用户点击取消执行的操作
      ElMessage.error("取消");
      // console.log(err);
    });
};

// 导出
const exportExcelAction = (val) => {
  if (datetime.value && datetime.value[0]) {
    contractDuration.value = datetime.value[0];
  }
  if (datetime.value && datetime.value[1]) {
    contractTermination.value = datetime.value[1];
  }
  if (creatTime.value && creatTime.value[0]) {
    projectCreateTime.value = creatTime.value[0];
  }
  if (creatTime.value && creatTime.value[1]) {
    projecEndTime.value = creatTime.value[1];
  }

  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    enterpriseName: enterpriseName.value,
    createContract: createContract.value,
    endInvestment: endInvestment.value,
    projectCreateTime: projectCreateTime.value,
    projecEndTime: projecEndTime.value,
    createInvestment: createInvestment.value,
    contractTermination: contractTermination.value,
    industry: industry.value && industry.value.join(),
  };
  params["addressList"] = addressList.value && addressList.value.join();

  if (val) {
    for (let key in val) {
      if (val[key]) {
        params[key] = val[key];
      }
    }
  }
  proxy.download(
    "/project/transfer/export",
    params,
    `项目立项_${
      new Date().getFullYear() +
      "-" +
      new Date().getMonth() +
      1 +
      "-" +
      new Date().getDate()
    }.xlsx`
  );
};
const route = useRoute();

// 获取立项列表
const approvalData = async () => {
  if (datetime.value && datetime.value[0]) {
    contractDuration.value = datetime.value[0];
  }
  if (datetime.value && datetime.value[1]) {
    contractTermination.value = datetime.value[1];
  }
  if (creatTime.value && creatTime.value[0]) {
    projectCreateTime.value = creatTime.value[0];
  }
  if (creatTime.value && creatTime.value[1]) {
    projecEndTime.value = creatTime.value[1];
  }

  if (datetime.value === null) {
    contractDuration.value = "";
    contractTermination.value = "";
  }
  if (creatTime.value === null) {
    projectCreateTime.value = "";
    projecEndTime.value = "";
  }
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    enterpriseName: enterpriseName.value,
    projectCreateTime: projectCreateTime.value,
    projecEndTime: projecEndTime.value,
    createInvestment: createInvestment.value,
    endInvestment: endInvestment.value,
    contractDuration: contractDuration.value,
    contractTermination: contractTermination.value,
    industry: industry.value && industry.value.join(),
  };
  params["addressList"] = addressList.value && addressList.value.join();
  if (paramsSubmit) {
    for (let key in paramsSubmit) {
      if (paramsSubmit[key]) {
        params[key] = paramsSubmit[key];
      }
    }
  }

  if (route.query.address) {
    params["address"] = route.query.address;
  }
  const res = await approvalList(params);
  // console.log(res);
  if (res.code === 200 && res.rows.length >= 0) {
    list.value = res.rows;
    total.value = res.total;
  }
  loading.value = false;
};
// 重置
const reset = (val) => {
  val = "";
  addressList.value = [];
  enterpriseName.value = "";
  datetime.value = "";
  (createInvestment.value = ""), (endInvestment.value = "");
  creatTime.value = "";
  projectCreateTime.value = "";
  projecEndTime.value = "";
  contractDuration.value = "";
  contractTermination.value = "";
  datetime.value = "";
  industry.value = "";
  approvalData();
};
let paramsSubmit;
// 查询
const onSubmit = (val) => {
  val.projectCreateTime = formatDate(val.projectCreateTime);
  paramsSubmit = val;
  approvalData();
};
// 切换每页条数
const handleSizeChange = (valueSise) => {
  pageSize.value = valueSise;
  approvalData();
};
// 切换页码
const handleCurrentChange = (valuePage) => {
  pageNum.value = valuePage;
  approvalData();
};

onMounted(async () => {
  await approvalData();
  await businessTypeOptions();
  await handelLocation();
  await handelIndustry();
});
</script>

<style scoped lang="scss">
.container {
  padding: 20px;
}
</style>
